<template>
  <div class="role-container">
    <div class="left-wrapper">
      <div v-for="(item,index) in roleList" :key="item.roleId" class="role-item" :class="{active: index === acitveIndex}" @click="change(index,item.roleId)">
        <div class="role-info">
          <svg-icon icon-class="user" class="icon" />
          {{ item.roleName }}
        </div>
        <el-dropdown>
          <div class="more">
            <svg-icon icon-class="more" />
          </div>
          <el-dropdown-menu>
            <!-- 第三方组件默认没有原生事件，需要添加.native修饰符 -->
            <el-dropdown-item @click.native="$router.push(`/sys/role/add/${item.roleId}`)">编辑角色</el-dropdown-item>
            <el-dropdown-item @click.native="deleteRole(item.roleId)">删除角色</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
      <el-button class="addBtn" size="mini" @click="$router.push('/sys/role/add')">添加角色</el-button>
    </div>
    <div class="right-wrapper">
      <!-- 利用tabs组件快速实现标题及内容切换 -->
      <el-tabs v-model="activeName">
        <el-tab-pane label="功能权限" name="tree">
          <div class="tree-wrapper">
            <div v-for="(item,index) in treeDatas" :key="item.id" class="tree-item">
              <div class="tree-title"> {{ item.title }} </div>
              <!-- 要检查树状数据是否是数组？ -->
              <!-- 如果有多个元素使用了相同的ref名称，则this.$refs会返回一个数组，包含所有这些元素 -->
              <el-tree
                ref="tree"
                :data="item.children"
                :props="defaultProps"
                default-expand-all
                :expand-on-click-node="false"
                :default-checked-keys="checkedKeys[index]"
                show-checkbox
                node-key="id"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane :label="`成员列表(${total})`" name="user">
          <el-table :data="userList" style="width: 100%">
            <el-table-column label="序号" type="index" width="200px" />
            <el-table-column label="员工姓名" prop="name" width="300px" />
            <el-table-column label="登录账号" prop="userName" />
          </el-table>
          <!-- 分页 -->
          <el-row type="flex" justify="end">
            <el-pagination
              :current-page="params.page"
              :page-size="params.pageSize"
              layout="total, prev, pager, next,sizes "
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { deleteRoleAPI, getRoleListAPI, getRolePermisionAPI, getRoleUserAPI, getTreeDataAPI } from '@/api/system'

export default {
  name: 'Role',
  data() {
    return {
      roleList: [], // 角色列表
      acitveIndex: 0, // 高亮下标
      treeDatas: [], // 所有树状数据
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      checkedKeys: [],
      activeName: 'tree', // 默认打开tree界面
      userList: [],
      total: 0,
      params: {
        page: 1,
        pageSize: 10,
        roleId: ''
      }
    }
  },
  async created() {
    await this.getRoleList()
    await this.getTreeData()
    // 初始化时，默认选中第一个角色
    this.getRolePermision(this.roleList[0].roleId)
    // 初始化时，获取第一个角色的成员列表
    this.params.roleId = this.roleList[0].roleId
    this.getRoleUser(this.params)
  },
  methods: {
    // 删除角色
    async deleteRole(id) {
      await this.$confirm('确认删除该角色吗?')
      await deleteRoleAPI(id)
      this.getRoleList()
      this.$message.success('删除成功')
    },
    handleSizeChange(val) {
      this.params.pageSize = val
      this.getRoleUser(this.params)
    },
    handleCurrentChange(val) {
      this.params.page = val
      this.getRoleUser(this.params)
    },
    // 获取角色成员列表
    async getRoleUser(params) {
      const res = await getRoleUserAPI(params)
      // console.log(res)
      this.userList = res.data.rows
      this.total = res.data.total
    },
    // 通过不同角色的id获取对应的权限列表
    async getRolePermision(roleId) {
      const res = await getRolePermisionAPI(roleId)
      this.checkedKeys = res.data.perms
      // 如果有多个元素使用了相同的ref名称，则this.$refs会返回一个数组，包含所有这些元素
      const treeList = this.$refs.tree
      treeList?.forEach((item, index) => {
        item.setCheckedKeys(this.checkedKeys[index], false)
      })
    },
    // 切换角色重新获取角色权限列表
    async change(index, id) {
      this.acitveIndex = index
      this.params.roleId = id
      await this.getRolePermision(id)
      await this.getRoleUser(this.params)
    },
    // 利用递归，给所有的树状数据添加禁用属性
    addDisabled(data) {
      data.forEach(item => {
        item.disabled = true
        if (item.children) {
          this.addDisabled(item.children)
        }
      })
    },
    // 获取角色列表
    async getRoleList() {
      const res = await getRoleListAPI()
      this.roleList = res.data
    },
    // 获取右侧树状权限数据
    async getTreeData() {
      const res = await getTreeDataAPI()
      this.treeDatas = res.data
      // 给所有的树状数据添加禁用属性
      this.addDisabled(this.treeDatas)
    }
  }
}
</script>

<style scoped lang="scss">
.role-container {
  display: flex;
  font-size: 14px;
  background-color: #fff;
  padding:20px;
  .left-wrapper {
    width: 200px;
    border-right: 1px solid #e4e7ec;
    padding: 4px;
    text-align: center;

    .role-item {
      position: relative;
      height: 56px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20px;
      cursor: pointer;

      &.active {
        background: #edf5ff;
        color: #4770ff;
      }
    }

    .role-info {
      display: flex;
      align-items: center;

      .icon {
        margin-right: 10px;
      }
    }

    .more {
      display: flex;
      align-items: center;
    }
    .addBtn{
      width: 100%;
      margin-top: 20px;
    }
  }

  .right-wrapper {
    flex: 1;

    .tree-wrapper {
      display: flex;
      justify-content: space-between;

      .tree-item {
        flex: 1;
        border-right: 1px solid #e4e7ec;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }

    ::v-deep .el-tabs__nav-wrap {
      padding-left: 20px;
    }

    .user-wrapper{
      padding:20px;
    }
  }
}
</style>
